<%@page import="java.awt.Font"%>
<%@page import="org.jfree.chart.labels.StandardCategoryToolTipGenerator" %>
<%@page import="java.awt.Color" %>
<%@page import="java.net.URLEncoder"%>
<%@ page import="java.util.LinkedList"%>
<%@page import="java.io.*" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="javax.xml.parsers.DocumentBuilderFactory,javax.xml.parsers.DocumentBuilder,
					org.w3c.dom.*"%>
<%@page import ="org.jfree.data.category.*"%>
<%@page import="org.jfree.chart.*" %>
<%@page import="org.jfree.chart.servlet.ServletUtilities" %>
<%@page import="org.jfree.chart.entity.*" %>
<%@page import ="org.jfree.chart.JFreeChart"%>
<%@page import ="org.jfree.chart.plot.SpiderWebPlot" %>
<%@page import ="org.jfree.chart.title.*" %>
<%@page import ="org.jfree.ui.RectangleEdge" %>
<%@page import ="ctm.javacode.mySpiderWebPlot" %>
<%@page import="java.text.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>中醫體質評量系統</title>
<script language="Javascript" type="text/javascript">
//防止使用者對於歷史問卷radio按鈕亂按情形(Qtype題目型別,q是題目,r是使用者填的答案)
function check1(Qtype,q,r){
	var Qt = Qtype;
	var ques = q;
	var record = r;
	var i=0;
	var obj = document.getElementsByName("type"+Qt+ques);
	while(i < obj.length){
		if(obj[i].value != record){
			obj[i].checked = false;
		}
		else{
			obj[i].checked = true;
		}
		i++;
	}	
}
</script>
<style type="text/css">
<!--
body {
	background-image: url(img/grass.jpg);
    background-position: center top;
	background-color: #FFFFFF;
	background-repeat: repeat;
}
body,td,th {
	color: #000000;
	font-size:24px;
	font-family: Arial;
}


a:link {
text-decoration:none;
font-family:Arial;
font-size:20px;
color:#FFFFFF;
}
a:visited {
text-decoration:none;
font-family:Arial;
font-size:20px;
color:#FFFFFF;
}
a:hover {
text-decoration:none;
font-family:Arial;
font-size:20px;
color:#000000;
}


.ind:link {
color: #535353;
text-decoration:none;
font-family:"標楷體";
font-size:18px;
}
.ind:visited {
color:#535353;
text-decoration:none;
font-family:"標楷體";
font-size:18px;
}

.ind:hover {
color:#BB280F;
text-decoration:none;
font-family:"標楷體";
font-size:18px;
}


.HEAD_STYLE {
	font-weight:bold;
	color: #1B4001;
	font-family:"標楷體";
	font-size:30px; 
}
.HEAD_STYLE_1 {
	font-weight:bold;
	color:#193940;
	font-family:"標楷體";
	font-size:24px; 
}
.TEXT_STYLE {
	font-family:Arial;
	color:#193940;
	font-size:24px;
	font-weight:bold;
}
.TEXT_STYLE_1 {
	font-family:標楷體;
	font-size:28px;
	font-weight:bold;
}
.TEXT_STYLE_2 {
	font-family:標楷體;
	font-size:25px;
	font-weight:bold;
}
.BOTTOM_STYLE {
	color: #FFFFFF; 
	font-family: Arial; 
	font-size:20px;
}
.LEFT_BUTTON {
	font-family:"標楷體"; 
	font-size:30px;
}
.button
{
	border:1px;
	padding-top: 4px;
	padding-right: 7px;
	padding-bottom: 4px;
	padding-left: 7px;
	background-color: #468129;
	color: #FFFFFF;
	font-size: 16px;
	border-color: #3C7023;
}
-->
</style>

</head>
<body alink="#FF0000" vlink="#FF0000">
<table width="100%" border="0">
		<tr>
			<td><p>&nbsp;</p></td>
		</tr>
				
			
			
		
 
    		<td width="5%">&nbsp;</td>
			
			<td bgcolor="#FFFFFF"><table width="100%" border="0">
      			<tr>
        			<td background="img/herbal.jpg">
						<p>&nbsp;</p>
          				<p>&nbsp;</p>
          				<p>&nbsp;</p>
          				<p>&nbsp;</p>
		  				<p>&nbsp;</p>
          
          			</td>
			  </tr>
     
	 
	 
	 			
	  			  <tr>
        			<td>
        			<%if (request.isUserInRole("user")) { %>	
						<table bgcolor="#437A27" width="100%" border="0">
         					 <tr>
            					<td>&nbsp;</td>
            					
								<td width="20%" align="center"><a href="main.jsp" target="_parent">回到主選單</a></td>
           			 			
          			 		</tr>
        				</table>
        			<%}else{ %>
         					<tr>
            					<td>&nbsp;</td>           					          			 			
          			 		</tr>
        			<%} %>
					</td>
     			  </tr>
      			
	  			
	  
	  
	  
	 			  <tr>
        				<td>
							<table width="100%">
           						<tr>
									<td valign="top">
										<table width="100%">
											
								
											<tr>
												
											<td>
<%
String loginName = "";
if (request.isUserInRole("admin")|| request.isUserInRole("professional")) {
	loginName = "/" +request.getParameter("Id");
}else{
	loginName = (request.getSession().getAttribute("login")).toString();
}
   	String filename = request.getParameter("filename");
	String category = new String(request.getParameter("category").getBytes("ISO-8859-1"));
	//System.out.print(category+"\n");
%>
<% //讀user所填的歷史問卷資料(xml)
	Document history = null;
	File file = new File("C:/history/general/"+loginName+"/"+filename+".xml");
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	try{
		DocumentBuilder builder = factory.newDocumentBuilder();
		history = builder.parse(file);
		
	}catch(Exception e){
		out.print("XML analysis error" + e.getMessage());
	}
	
	int quesflag=0,tranValueflag=0,typePrintflag=0;
	LinkedList<String> QuesFromtype = new LinkedList<String>(); //放每個類型的題目
	LinkedList<String> AnsFromtype = new LinkedList<String>(); //放user填的每個類型題目之答案
	LinkedList<String> ClassForValue = new LinkedList<String>(); //型別(中文)
	LinkedList<Double> transValue = new LinkedList<Double>();  //放user填完答案問卷之分數結果
	LinkedList<String> typeForPrint = new LinkedList<String>(); //放user體值判斷的結果
	LinkedList<String> depenOn = new LinkedList<String>();//放此症狀需要先行依據什麼體質
	
	Element elementforUser = history.getDocumentElement();
	NodeList list1 = elementforUser.getChildNodes();
	for(int i=0 ; i<list1.getLength();i++){
		 Node temp1 = list1.item(i);
		 if(isTextNode(temp1)){
			 continue;
		 }
		 if(temp1.getNodeName() == "question"){
			 quesflag = 1;
		 }
		 if(temp1.getNodeName() == "transValue"){
			 tranValueflag = 1;
		 }
		 if(temp1.getNodeName() == "typePrint"){
			 typePrintflag = 1;
		 }
		 NodeList nodes2 = temp1.getChildNodes();
		 for(int j=0;j < nodes2.getLength();j++){
			 Node temp2 = nodes2.item(j);
			 if(isTextNode(temp2)){
				 continue;
			 }
			 if(quesflag == 1 && temp2.hasChildNodes()){
				 QuesFromtype.add(temp2.getNodeName());
				 AnsFromtype.add(temp2.getFirstChild().getNodeValue());
			 }
			 if(tranValueflag == 1 && temp2.hasChildNodes()){
				NamedNodeMap attrlist4 = temp2.getAttributes();
				if(attrlist4 != null){
					depenOn.add(attrlist4.getNamedItem("depend").getNodeValue());
				}
				ClassForValue.add(temp2.getNodeName());
				transValue.add(Double.parseDouble(temp2.getFirstChild().getNodeValue()));
			 }
			 if(typePrintflag == 1 && temp2.hasChildNodes()){
				 typeForPrint.add(temp2.getFirstChild().getNodeValue());
			 }
		 }
		 quesflag = 0;
		 tranValueflag = 0;
		 typePrintflag = 0;
	}
	//System.out.println(depenOn);
%>
<%
	String File3 = request.getRealPath("./WEB-INF/questionCategory.xml");
	Document CataDom = null;
	DocumentBuilderFactory factory3 = DocumentBuilderFactory.newInstance();
	try{
		DocumentBuilder builder3 = factory3.newDocumentBuilder();
		CataDom = builder3.parse(File3);
	}catch(Exception e){
		out.print("XML analysis error" + e.getMessage());
	}
%>
<%
	String fileName="";
	Element element2 = CataDom.getDocumentElement();
	NodeList list = element2.getChildNodes();
	for(int i=0 ; i < list.getLength() ; i++){
		Node temp1 = list.item(i);
		if(isTextNode(temp1)){
			continue;
		}
		NodeList list2 = temp1.getChildNodes();
		for(int j=0 ; j < list2.getLength() ; j++){
			Node temp2 = list2.item(j);
			if(isTextNode(temp1)){
				continue;
			}
			if(temp2.getNodeName().equals(category)){
				fileName = temp2.getFirstChild().getNodeValue();
				break;
			}
		}
	}
%>	
<%
	//讀對應的問卷題目(xml)
	String path;
	path = "./WEB-INF/"+fileName+".xml";
	Document BookDom = null;
	String File2 = request.getRealPath(path);
	DocumentBuilderFactory factory2 = DocumentBuilderFactory.newInstance();
	
	try{
		DocumentBuilder builder = factory2.newDocumentBuilder();
		BookDom = builder.parse(File2);
		
	}catch(Exception e){
		out.print("XML analysis error" + e.getMessage());
	}
	
	int questionflag=0,marklistflag=0;
	LinkedList<String> questions = new LinkedList<String>(); //放題目
	LinkedList<String> marklists = new LinkedList<String>(); //放等級
	LinkedList<String> CLASS = new LinkedList<String>();//放型別
	LinkedList<String> CLASSforQ = new LinkedList<String>();//放根據型別的題目
	LinkedList<String> ValueforLevels = new LinkedList<String>();//放各答案等級所得到的分數
	
	Element element = BookDom.getDocumentElement();
	NodeList nodes1 = element.getChildNodes();
	for(int i=0;i < nodes1.getLength() ; i++){
		Node temp1 = nodes1.item(i);
		NamedNodeMap attrlist1 = temp1.getAttributes();
		if(attrlist1 != null)
		{
			//System.out.println(attrlist1.item(0).getNodeName());
			//System.out.println(attrlist1.item(0).getNodeValue());
		}
		if(isTextNode(temp1)){
			continue;
		}
		if(temp1.getNodeName() == "QUESTION"){
			questionflag=1;
		}
		if(temp1.getNodeName() == "MARKLIST"){
			marklistflag=1;
		}
		NodeList nodes2 = temp1.getChildNodes();
		for(int j=0;j < nodes2.getLength();j++){
			Node temp2 = nodes2.item(j);
			NamedNodeMap attrlist2 = temp2.getAttributes();
			if(attrlist2 != null && temp2.getNodeName() == "CLASS"){
				CLASS.add(attrlist2.item(0).getNodeValue());
				//System.out.println(attrlist2.item(0).getNodeName());
				//System.out.println(attrlist2.item(0).getNodeValue());
			}
			if(attrlist2 != null && marklistflag == 1){
				ValueforLevels.add(attrlist2.item(0).getNodeValue());	
				//System.out.println(attrlist2.item(0).getNodeValue());
			}
			if(isTextNode(temp2)){
				continue;
			}
			if(questionflag == 1){
				questions.add(temp2.getFirstChild().getNodeValue());
			}
			if(marklistflag == 1){
				marklists.add(temp2.getFirstChild().getNodeValue());
				//System.out.println(marklists.peekLast());
			}
			if(temp2.hasChildNodes() && temp2.getNodeName() == "CLASS"){
				NodeList nodes3 = temp2.getChildNodes();
				for(int k=0; k<nodes3.getLength();k++){
					Node temp3 = nodes3.item(k);
					if(isTextNode(temp3)){
						continue;
					}
					CLASSforQ.add(temp3.getNodeName());
					//System.out.println(":"+CLASSforQ.peekLast());
				}
				CLASSforQ.add("end");
				//System.out.println(":"+CLASSforQ.peekLast());
			}

		}
		questionflag = 0;
		marklistflag = 0;
	}
	//將讀進來的體質由中文轉變成英文(供radio按鈕命名用)
	String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	LinkedList<String> CLASStoEng = new LinkedList<String>();//放型別(英文型式)
	for(int i=0 ; i < CLASS.size();i++){
		CLASStoEng.add(alphabet.substring(i, i+1));
	}
%>	
<%!
	public boolean isTextNode(Node node){
		return node.getNodeName().equals("#text");
	}
%>
<%
	int j=0,count=0,levels=0,id=0,count1=0,record=0;
	String s,s1,s2;
	for(int i=0;i<CLASS.size();i++){
%>
		<center><font size="5" style="font: bold normal bold 18pt/30pt '標楷體'" color="66CC33"><%= CLASS.get(i) %></font></center>
		<br>
		<table width="900" height="146" border="2" align="center">
				<tr bgcolor="FFFF99">
					<td>請根據近一年的體驗和感覺,回答下列問題</td>
<%
		while(levels < marklists.size()){
			s = marklists.get(levels);
			s1 = s.substring(0,2);
			s2 = s.substring(2);
%>
					<td align="center" width="170"><%= s1 %><br/><%= s2 %></td>
<%
			levels++;
		}
		levels=0;
%>
				</tr>
<% 				
		while(j < CLASSforQ.size()){
			if(CLASSforQ.get(j).equals("end")){				
				break;
			}
			String ques = CLASSforQ.get(j).substring(1);
			record = check(CLASStoEng.get(i),ques,QuesFromtype,AnsFromtype);
			if(count<9){
%>
			<tr><td width="712" height="52"><%= "(0"+(count+1)+")" %><%= questions.get((Integer.parseInt(ques))-1) %></td>
<%
			}
			else{
%>
			<tr><td width="712" height="52"><%= "("+(count+1)+")" %><%= questions.get((Integer.parseInt(ques))-1) %></td>
<%
			}
			while(levels < marklists.size()){
%>		
				<td><input type="radio" name="type<%=CLASStoEng.get(i)%><%= ques%>" value="<%= ValueforLevels.get(levels) %>" <% if(record == Integer.parseInt(ValueforLevels.get(levels))){%> checked="checked"<%}%> onClick="check1('<%= CLASStoEng.get(i) %>','<%= ques %>',<%= record%>)"/></td>
<%
				levels++;
			}
			count++;
			levels=0;
%>
			</tr>
<%
			record=0;
			j++;
		}
%>
		</table>
		<br>
<%
		j++;
		count=0;
		levels=0;
	}
%>
<%!
	public int check(String Class,String ques,LinkedList<String> QuesFromtype,LinkedList<String> AnsFromtype){
		int record=0;
		String type = "type"+Class+ques;
		for(int i=0;i<QuesFromtype.size();i++){
			if(QuesFromtype.get(i).equals(type)){
				record = Integer.parseInt(AnsFromtype.get(i));
				break;
			}
			else;
		}		
		return record;
	}
%>
<%!
/*
	public boolean check(String Class,String ques,LinkedList<String> QuesFromtype,LinkedList<String> AnsFromtype,int value){
		boolean flag = false;
		String type;
		for(int i=0;i<QuesFromtype.size();i++){
			type = "type"+Class+ques;
			if(QuesFromtype.get(i).equals(type)){
				if(Integer.parseInt(AnsFromtype.get(i)) == value){
					flag = true;
				}
				break;
			}
			else;
		}
		return flag;
	}
*/
%>
<center><font color="66CC33" size="5" class="HEAD_STYLE" style="font: bold normal bold 24pt/36pt '標楷體'">體質評量結果(依分數由高至低排列)</font>
<br><br></center>
<center>	
<%	//印出屬於哪種體質
	boolean firstTrend = true,firstBasic = true,firstBelong=true;
	for(int i=0;i<typeForPrint.size();i++){
		if(typeForPrint.get(i).contains("傾向")){
			if(firstTrend){
%>
<center><br><font class="TEXT_STYLE_1">您傾向擁有</font></center><br>
<%
				firstTrend = false;
			}
%>
<font style="color:blue" class="TEXT_STYLE_2"><%= typeForPrint.get(i).substring(2) %></font>
<%					
		}
		else if(typeForPrint.get(i).contains("基本是")){
			if(firstBasic){
%>
<center><br><font class="TEXT_STYLE_1">您基本上是</font></center><br>
<%
			  	firstBasic = false;
			}
%>
<font style="color: red" class="TEXT_STYLE_2"><%= typeForPrint.get(i).substring(3) %></font>					
<%
		}
		else{
			if(firstBelong){
%>
<center><font class="TEXT_STYLE_1">您擁有</font></center><br>
<%		
				firstBelong = false;
			}
%>
<font style="color:red" class="TEXT_STYLE_2"><%= typeForPrint.get(i) %></font>	
<%	
		}
	}
%>
	</center>
<%	//Show出九種體質雷達圖
	DefaultCategoryDataset dataset = new DefaultCategoryDataset();
	String group1="";
	
	int index=0;
	while(index < transValue.size() && index < ClassForValue.size()){
		if(depenOn.get(index).equals("no")){
			dataset.addValue(transValue.get(index), group1 ,ClassForValue.get(index)+"("+(int)Math.round(transValue.get(index))+")");
		}
		index++;
	}
	mySpiderWebPlot spiderwebplot = new mySpiderWebPlot(dataset);
	spiderwebplot.setMaxValue(100);
    spiderwebplot.setAxisLinePaint(Color.blue);
    spiderwebplot.setInteriorGap(0.3);
	///////////以下兩行是為了滑鼠移到點上時,只要顯示分數
  	StandardCategoryToolTipGenerator  tooltip = new StandardCategoryToolTipGenerator("{2}",NumberFormat.getInstance());
  	spiderwebplot.setToolTipGenerator(tooltip);
  	////////////////////////////
    spiderwebplot.setLabelFont(new Font("標楷體", Font.BOLD, 20));
	JFreeChart jfreechart = new JFreeChart("", TextTitle.DEFAULT_FONT,spiderwebplot, false);
	final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
	LegendTitle legendtitle = new LegendTitle(spiderwebplot);
	legendtitle.setPosition(RectangleEdge.BOTTOM);
	jfreechart.addSubtitle(legendtitle);
	          String fname = ServletUtilities.saveChartAsJPEG(jfreechart, 600, 400, info, session);
	PrintWriter pw = new PrintWriter(out);
	ChartUtilities.writeImageMap(pw, fname, info, false);
	pw.flush();
	String chartURL = request.getContextPath() + "/servlet/DisplayChart?filename=" + fname;
	
%>
<%
	LinkedList<Double> symptomTransValue = new LinkedList<Double>();
	LinkedList<String> symptom = new LinkedList<String>();
	LinkedList<String> RadarPath = new LinkedList<String>();
	String consti;
	for(int i = 0;i <typeForPrint.size();i++){
		consti = typeForPrint.get(i);
		for(int z=0;z < depenOn.size();z++){
			if(consti.contains(depenOn.get(z))){
				symptomTransValue.add(transValue.get(z));
				symptom.add(ClassForValue.get(z));
			}
		}
		if(symptomTransValue.size() != 0 && symptom.size() != 0){
			RadarPath = drawRadar(RadarPath,consti,symptomTransValue,symptom,out,request,session);
		}
		symptomTransValue.clear();
		symptom.clear();
	}
%>
<br><center><font color="3333FF" size="5" class="HEAD_STYLE_1" style="font: bold normal bold 20pt/32pt '標楷體'">體質評量雷達圖</font><br>
</center>
<center><IMG SRC="<%= chartURL %>" WIDTH="600" HEIGHT="400" BORDER="0" USEMAP="#<%= fname %>"></center><br>
<%
	int i=0;
	if(category.equals("五臟體質類型")||category.equals("五臟體徵類型"))
	{
	while(i<RadarPath.size()){
%>
		<center><font color="3333FF" size="5" class="HEAD_STYLE_1" style="font: bold normal bold 20pt/32pt '標楷體'"><%=  RadarPath.get(i++)%>評量雷達圖</font><br></center>
		<center><IMG SRC="<%= RadarPath.get(i++) %>" WIDTH="600" HEIGHT="400" BORDER="0" USEMAP="#<%= RadarPath.get(i++) %>"></center><br>
<%
	}}
%>
<%!
	public LinkedList<String> drawRadar(LinkedList<String> RadarPath,String consti,LinkedList<Double> symptomTransValue,LinkedList<String> symptom,JspWriter out,
			HttpServletRequest request,HttpSession session) throws Exception{
		DefaultCategoryDataset symptomDataset = new DefaultCategoryDataset();
		String symptomGroup="";
		
		int index=0;
		while(index < symptomTransValue.size() && index < symptom.size()){
			symptomDataset.addValue(symptomTransValue.get(index), symptomGroup ,symptom.get(index)+"("+(int)Math.round(symptomTransValue.get(index))+")");
			index++;
		}
		while(index < 3){
			symptomDataset.addValue(0, symptomGroup ,"");
			index++;
		}
		mySpiderWebPlot spiderwebplot = new mySpiderWebPlot(symptomDataset);
		spiderwebplot.setMaxValue(100);
		spiderwebplot.setAxisLinePaint(Color.blue);
		spiderwebplot.setInteriorGap(0.3);
		///////////以下兩行是為了滑鼠移到點上時,只要顯示分數
		StandardCategoryToolTipGenerator  tooltip = new StandardCategoryToolTipGenerator("{2}",NumberFormat.getInstance());
		spiderwebplot.setToolTipGenerator(tooltip);
		////////////////////////////
		spiderwebplot.setLabelFont(new Font("標楷體", Font.BOLD, 22));
		JFreeChart jfreechart = new JFreeChart("", TextTitle.DEFAULT_FONT,spiderwebplot, false);
		final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
		LegendTitle legendtitle = new LegendTitle(spiderwebplot);
		legendtitle.setPosition(RectangleEdge.BOTTOM);
		jfreechart.addSubtitle(legendtitle);
		          String fname = ServletUtilities.saveChartAsJPEG(jfreechart, 600, 400, info, session);
		PrintWriter pw = new PrintWriter(out);
		ChartUtilities.writeImageMap(pw, fname, info, false);
		pw.flush();
		String chartURL = request.getContextPath() + "/servlet/DisplayChart?filename=" + fname;
		if(consti.contains("傾向")){
			consti = consti.substring(2);	
		}
		RadarPath.add(consti);
		RadarPath.add(chartURL);
		RadarPath.add(fname);
		return RadarPath;
	}
%>
<%if (request.isUserInRole("user")) { %>
<center><input  class="button" type="button" value="回上一頁" onClick="location='history.jsp'"/>
<input  class="button" type="button" value="回到主選單" onClick="location='main.jsp'"/></center>
<%} %>
</td>
											</tr>
											
										</table>
									
             

		
											
								  </td>
									

								</tr>
       					 </table>
         

         				</td>
			  </tr>
   
	  
					 <tr>
      					  
   					    <td><p>&nbsp;</p></td>
  					 </tr>
	  				
					<tr>
      					  <td bgcolor="#437A27"><div align="center" class="BOTTOM_STYLE">Copyright@ITRI and CCU_PLlab</div></td>
   
			  </tr>
    						
  	 			  
	
			</table>
		</td>
	    
		<td width="5%">&nbsp;</td>
</table>
<p>&nbsp;</p>
</body>
</html>